﻿using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Prism.Ioc;
using Prism.Commands;
using Prism.Regions;
using WPFNote.Models;
using WPFNote.Services.IDal;
using WPFNote.Utilities.Common;
using WPFNote.Utilities.Extensions;
using WPFNote.Utilities.ReturnJson;

namespace WPFNote.ViewModels
{
    public class NoteAddViewModel : NavigationViewModel
    {
        private readonly INote _note;
        private readonly ICategory _category;
        private readonly IDialogHostService _dialogHost;
        private readonly IRegionManager _regionManager;

        public DelegateCommand BackCommand { get; private set; }
        public DelegateCommand SaveCommand { get; private set; }

        #region 属性

        private int _categoryId;

        public int CategoryId
        {
            get => _categoryId;
            set
            {
                _categoryId = value;
                RaisePropertyChanged();
            }
        }

        private string _title;

        public string Title
        {
            get => _title;
            set
            {
                _title = value;
                RaisePropertyChanged();
            }
        }

        private string _content;

        public string Content
        {
            get => _content;
            set
            {
                _content = value;
                RaisePropertyChanged();
            }
        }

        private string _categoryName;

        public string CategoryName
        {
            get => _categoryName;
            set
            {
                _categoryName = value;
                RaisePropertyChanged();
            }
        }

        private Category _categorySelected;

        public Category CategorySelected
        {
            get => _categorySelected;
            set
            {
                _categorySelected = value;
                RaisePropertyChanged();
            }
        }

        private List<Category> _categories;

        public List<Category> Categories
        {
            get => _categories;
            set
            {
                _categories = value;
                RaisePropertyChanged();
            }
        }

        #endregion

        public NoteAddViewModel(IContainerProvider containerProvider, IRegionManager regionManager, INote note,
            ICategory category, IRegionNavigationJournal journal) : base(containerProvider)
        {
            _regionManager = regionManager;
            _note = note;
            _category = category;
            SaveCommand = new DelegateCommand(Save);
            BackCommand = new DelegateCommand(() =>
            {
                _regionManager.RequestNavigate(PrismManager.MainViewRegionName, "Index", new NavigationParameters()
                {
                    {
                        "id", CategoryId
                    }
                });
            });
            _dialogHost = containerProvider.Resolve<IDialogHostService>();
        }

        /// <summary>
        /// 获取分类列表
        /// </summary>
        private async void GetCategoryList()
        {
            var result = await _category.SelectListAsync(new CategorySch());
            Categories = result;
            RaisePropertyChanged(nameof(Categories));
            if (Categories.Count == 0)
            {
                return;
            }

            CategorySelected = CategoryId > 0 ? Categories.FirstOrDefault(x => x.Id == CategoryId) : Categories[0];
        }

        private async void Save()
        {
            if (string.IsNullOrWhiteSpace(Title))
            {
                Aggregator.SendMessage("请填写标题");
                return;
            }

            if (CategoryId < 1 && string.IsNullOrWhiteSpace(CategoryName))
            {
                Aggregator.SendMessage("请选择分类或填写一个新的分类");
                return;
            }

            if (string.IsNullOrWhiteSpace(Content))
            {
                Aggregator.SendMessage("请填写笔记内容");
                return;
            }

            // 如果分类名称不为空，则根据分类名称获取分类信息，如果获取不到，则创建新的分类
            if (!string.IsNullOrWhiteSpace(CategoryName))
            {
                var category = await _category.SelectAsync(new CategorySch()
                    { UserId = AppSession.UserInfo.Id, Title = CategoryName, TypeId = AppSession.CategoryType });
                if (category != null)
                {
                    CategoryId = category.Id;
                }
                else
                {
                    CategoryId = await _category.InsertReturnIdAsync(new Category()
                    {
                        Title = CategoryName,
                        Sort = 99,
                        TypeId = AppSession.CategoryType,
                        UserId = AppSession.UserInfo.Id
                    });
                }
            }

            var result = await _note.InsertAsync(new Models.Note()
            {
                Title = Title,
                Content = Content,
                CategoryId = CategoryId,
                IsShow = true,
                IsTop = false,
                UserId = AppSession.UserInfo.Id,
                EditTime = DateTime.Now
            });
            if (result)
            {
                Aggregator.SendMessage("保存成功");
                _regionManager.RequestNavigate(PrismManager.MainViewRegionName, "Index", new NavigationParameters()
                {
                    {
                        "id", CategoryId
                    }
                });
            }
            else
            {
                Aggregator.SendMessage("保存失败");
            }
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            var dayReport = $@"**一、工作时间：**
{DateTime.Now:yyyy-MM-dd}
**二、完成事项：**
1.
2.
3.
**三、问题描述：**
今日无问题
";
            CategoryId = navigationContext.Parameters.GetValue<int>("categoryId");
            var isAddDayReport = navigationContext.Parameters.GetValue<bool>("isDayReport");
            Title = isAddDayReport ? DateTime.Today.ToString("yyyy-MM-dd") + " 工作内容" : string.Empty;
            Content = isAddDayReport ? dayReport : string.Empty;
            CategoryName = string.Empty;
            GetCategoryList();
        }
    }
}